import configparser
import os

class Config:

    def __init__(self):
        self.config_path = os.path.expanduser("~")+"/.config/invhnd/config.ini"
        self.make_config_dir()
        self.make_config_file()
        self.make_plugins_dir()

        self.parser = configparser.ConfigParser()
        self.parser.read(self.config_path)

    def is_config_exists(self):
        return os.path.exists(self.config_path)

    def make_config_file(self):
        if not self.is_config_exists():
            fp = open(self.config_path, 'w')
            fp.close()

    def make_config_dir(self):
        os.makedirs(os.path.dirname(self.config_path), exist_ok=True)

    def make_plugins_dir(self):
        os.makedirs(os.path.dirname(self.config_path) + '/plugins', exist_ok=True)

    def write_config(self):
        with open(self.config_path, 'w') as cfg:
            self.parser.write(cfg)

    def get_plugin_option(self, plugin_name, option):
        return self.parser.get(plugin_name, option)
      
    def has_section(self, section):
        return self.parser.has_section(section)

    def has_option(self, section, option):
        return self.parser.has_option(section, option)

    def add_plugin_option(self, plugin_name, option, value, rewrite=False):
        if rewrite or not self.has_option(plugin_name, option):
            if not self.has_section(plugin_name): 
                self.parser.add_section(plugin_name)
            self.parser.set(plugin_name, option, value)
            self.write_config()


